/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * http://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */
package com.dian.modules.sale.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dian.common.utils.*;

import com.dian.common.validator.ValidatorUtils;
import com.dian.common.validator.group.AddGroup;
import com.dian.common.validator.group.UpdateGroup;
import com.dian.modules.enums.sale.DeliverHead_DeliverStateEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dian.common.exception.RRException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections.CollectionUtils;
import com.dian.common.server.CommonService;
import com.dian.modules.sale.dao.DeliverHeadDao;

import com.dian.modules.sale.entity.DeliverLineEntity;
import com.dian.modules.sale.entity.DeliverHeadEntity;

import com.dian.modules.sale.service.DeliverHeadService;
import com.dian.modules.sale.service.DeliverLineService;

import com.dian.modules.sale.vo.DeliverHeadExportVO;
import com.dian.modules.sale.vo.DeliverLineExportVO;

/**
 * 销售发货单服务实现类
 *
 * @author xiaolai
 * @email xiaolai@9dyun.cn
 * @date 2019-06-21 16:00:09
 */
@Service("deliverHeadService")
public class DeliverHeadServiceImpl extends ServiceImpl<DeliverHeadDao, DeliverHeadEntity> implements DeliverHeadService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public CommonService commonService;

    @Autowired
    public DeliverLineService deliverLineService;

    /**
     * 销售发货单分页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<DeliverHeadEntity> page = this.page(new Query<DeliverHeadEntity>().getPage(params),getQueryWrapper(params) );
        return new PageUtils(page);
    }

    /**
    *  销售发货单新增
    * @param deliverHeadEntity
    * @return
    */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveInfo(DeliverHeadEntity deliverHeadEntity) {

        //设置编码，等基础默然初始化数据设置
        deliverHeadEntity.setDeliverDate(new Date());
        deliverHeadEntity.setDeliverNo(commonService.getCode(DeliverHeadEntity.class));

        //数据完整性校验
        this.paramsCheck(deliverHeadEntity,AddGroup.class);

        //保存主表
        this.save(deliverHeadEntity);

        //保存从表
        if (CollectionUtils.isNotEmpty(deliverHeadEntity.getDeliverLineEntityList())) {
            List<DeliverLineEntity> detailList = deliverHeadEntity.getDeliverLineEntityList();
            for (DeliverLineEntity detail : detailList) {
                detail.setDeliverId(deliverHeadEntity.getId());
            }
            deliverLineService.saveBatch(deliverHeadEntity.getDeliverLineEntityList());
        }
        return true;
    }

    /**
     *销售发货单更新
     * @param deliverHeadEntity
     * @return
     */
    @Override
    public boolean updateInfo(DeliverHeadEntity deliverHeadEntity) {

        //修改状态校验
        this.updateCheck(deliverHeadEntity.getId());

        //主表数据完整性校验
        this.paramsCheck(deliverHeadEntity, UpdateGroup.class);

        //更新主表
        this.updateById(deliverHeadEntity);

        //更新从表
        deliverLineService.updateInfo(deliverHeadEntity);


        return true;
    }

    /**
     *销售发货单删除
     * @param id
     * @return
     */
    @Override
    public boolean deleteInfo(Long id) {

        //删除状态校验
        this.deleteCheck(id);

        //更新从表
        deliverLineService.deleteInfo(id);

        //更新主表
        this.remove(new QueryWrapper<DeliverHeadEntity>().eq("id",id));

        return true;
    }

    /**
     * 销售发货单详情
     * @param id
     * @return
     */
    @Override
    public DeliverHeadEntity getInfo(Long id) {
        DeliverHeadEntity deliverHeadEntity =getById(id);
        List<DeliverLineEntity> lineList=deliverLineService.queryLineList(id);
        deliverHeadEntity.setDeliverLineEntityList(lineList);
        return deliverHeadEntity;
    }

    /**
     * 销售发货单审核
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkInfo(Long id) {
        DeliverHeadEntity deliverHeadEntity =this.getById(id);
        checkCheck(deliverHeadEntity);
        deliverHeadEntity.setDeliverState(DeliverHead_DeliverStateEnum.AUDITED.getValue());
        deliverHeadEntity.setCheckUserId(commonService.getUserId());
        deliverHeadEntity.setCheckUserName(commonService.getUserName());
        deliverHeadEntity.setCheckDate(new Date());
        return this.updateById(deliverHeadEntity);
    }

    /**
     *销售发货单当前页or全部导出
     * @param params
     * @return
     */
    @Override
    public List<DeliverHeadExportVO> exportList(Map<String, Object> params) {
        List<DeliverHeadEntity> list;
        Integer exprotType= PUtil.getParaToInt(params.get("exprotType"),0);
        if(exprotType==0){
            list= this.page(new Query<DeliverHeadEntity>().getPage(params),getQueryWrapper(params)).getRecords();
        }else{
            list= this.list(getQueryWrapper(params));
        }
        List<DeliverHeadExportVO> resultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)) {
            resultList = BeanConverter.convertList(list, DeliverHeadExportVO.class);
            // 封装明细
            if(CollectionUtils.isNotEmpty(resultList)){
                for(DeliverHeadExportVO deliverHeadEntity : resultList){
                    List<DeliverLineEntity>  deliverLineEntityList = deliverLineService.queryLineList(deliverHeadEntity.getId());
                    deliverHeadEntity.setDeliverLineExportVOList(BeanConverter.convertList( deliverLineEntityList, DeliverLineExportVO.class));
                }
            }
        }
        return resultList;
    }


    /***********************************************************************************************/
    /****************************************** 私有方法 ********************************************/
    /***********************************************************************************************/

    /**
     * 修改状态校验
     *
     * @param
     */
    private void updateCheck(Long id) {
        DeliverHeadEntity deliverHeadEntity =this.getById(id);
        if(deliverHeadEntity.getDeliverState().equals(DeliverHead_DeliverStateEnum.AUDITED.getValue())){
                 throw new RRException(String.format("[%s] 当前订单为已审核状态,禁止修改",deliverHeadEntity.getProbNo()));
         }
    }
    /**
     * 审核状态校验
     *
     * @param
     */
    private void checkCheck(DeliverHeadEntity deliverHeadEntity) {

        if(deliverHeadEntity.getDeliverState().equals(DeliverHead_DeliverStateEnum.AUDITED.getValue())){
           throw new RRException(String.format("[%s] 当前订单为已审核状态,禁止审核",deliverHeadEntity.getProbNo()));
        }
    }

    /**
     * 删除状态校验
     *
     * @param
     */
    private void deleteCheck(Long id) {
        DeliverHeadEntity deliverHeadEntity =this.getById(id);
       if(deliverHeadEntity.getDeliverState().equals(DeliverHead_DeliverStateEnum.AUDITED.getValue())){
            throw new RRException(String.format("[%s] 当前订单为已审核状态,禁止删除",deliverHeadEntity.getProbNo()));
       }
    }

    /**
     * 新增和修改参数校验
     *
     * @param record
     */
    private void paramsCheck(DeliverHeadEntity record, Class<?> cls) {

        //设置明细的主表ID
        ListUtils.setPropertyValue(record.getDeliverLineEntityList(),"deliver_id",record.getId());

        ValidatorUtils.validateEntity(record, cls);

        if (CollectionUtils.isEmpty(record.getDeliverLineEntityList())) {
            throw new RRException("销售发货单明细数据不能为空");
        }
        for (DeliverLineEntity deliverLineEntity : record.getDeliverLineEntityList()) {
            int index = record.getDeliverLineEntityList().indexOf(deliverLineEntity) + 1;
            try {
                ValidatorUtils.validateEntity(deliverLineEntity, cls);
            }catch (RRException e){
                throw new RRException(String.format("第%s行 预订单明细校验失败<br/>"+e.getMsg(), index));
            }
        }
    }

    /**
     * 获取查询条件
     *
     * @param
     */
    private QueryWrapper<DeliverHeadEntity> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<DeliverHeadEntity> queryWrapper=new QueryWrapper<>();
        if(!StrUtil.isBlankIfStr(params.get("deliverNo"))){
            queryWrapper.like("deliver_no",params.get("deliverNo"));
        }
        if(!StrUtil.isBlankIfStr(params.get("deliverDate"))){
            String deliverDate=String.valueOf(params.get("deliverDate"));
            String[] deliverDateRange=deliverDate.split("至");
            if(deliverDateRange.length==2){
                queryWrapper.gt("deliver_date",DateUtils.getBeginTimeOfDate(deliverDateRange[0]));
                queryWrapper.lt("deliver_date",DateUtils.getBeginTimeOfDate(deliverDateRange[1]));
            }else{
                queryWrapper.gt("deliver_date",DateUtils.getBeginTimeOfDate(deliverDate));
            }
        }
        if(!StrUtil.isEmptyIfStr(params.get("propKey"))){
            queryWrapper.and(wrapper -> wrapper
            );
        }
        if(!StrUtil.isBlankIfStr(params.get("probId"))){
            queryWrapper.eq("prob_id",params.get("probId"));
        }
        queryWrapper.orderByAsc("id");
        return queryWrapper;
    }
}
